package com.jeepig.common.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import com.jeepig.common.utils.sign.Base64;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * @ClassName SignUtils
 * @Description 签名工具类
 * @Author guoxb
 * @Date 2022/12/17
 * @Version 1.0
 **/
public class SignUtils {

    /**
     * 获取参数不为空值
     *
     * @param key defaultValue 要判断的value
     * @param signData 签名字段
     * @return String 返回值
     */
    public static String sign(String key,String signData) {
        try {
            Sign sign = SecureUtil.sign(SignAlgorithm.SHA256withRSA);
            // PrivateKey privateKey = SecureUtil.generatePrivateKey(SignAlgorithm.SHA256withRSA.name(),key.getBytes(StandardCharsets.UTF_8));
            Signature signature = Signature.getInstance(SignAlgorithm.SHA256withRSA.name());
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decode(key));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            //设置
            sign.setPrivateKey(privateKey);
            //签名
            byte[] signed = sign.sign(signData.getBytes(StandardCharsets.UTF_8));
            return Base64.encode(signed);
        }catch (NoSuchAlgorithmException noSuchAlgorithmException){
            noSuchAlgorithmException.printStackTrace();
        }catch (InvalidKeySpecException invalidKeySpecException){
            invalidKeySpecException.printStackTrace();
        }
        return null;
    }

    /**
     * 获取参数不为空值
     *
     * @param key 公钥
     * @return value 返回值
     */
    public static boolean verify(String key,String signData){
        Sign sign = SecureUtil.sign(SignAlgorithm.SHA256withRSA);
        //设置
        sign.setPublicKey(SecureUtil.generatePublicKey(SignAlgorithm.SHA256withRSA.name(),key.getBytes(StandardCharsets.UTF_8)));
        //验证签名
        return sign.verify(signData.getBytes(StandardCharsets.UTF_8),key.getBytes(StandardCharsets.UTF_8));
    }

}
